import { order_state_map } from '../../../utils/dataset/db_data'

Page({
  data: {
    refresher: 0,
    act: 0,
    orderList: [],
    tabs: [
      { label: '全部订单', searchData: {} },
      { label: '待支付', searchData: { order_state: 0 } },
      { label: '待使用', searchData: { order_state: 2 } },
      { label: '交易关闭', searchData: { order_state: 1 } },
      { label: '交易完成', searchData: { order_state: 3 } },
    ]
  },
  onLoad(options) {
    this.loadOrderData();
  },
  async loadOrderData(searchData) {
    wx.showLoading({ title: '加载中', mask: true })
    searchData = searchData || {};
    searchData.user_id = '<openid>';
    const resList = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_order',
        data: {
          funcName: 'query',
          searchText: '',
          searchData: searchData,
        },
        success: (r) => resolve(r.result),
      });
    })
    const hh = Array.apply(null, { length: 25 }).map((o, i) => {
      let s = '00' + i;
      return s.substring(s.length - 2);
    });
    const mm = ['00', '30'];
    const timeText = [];
    for (let i = 0; i <= 48; i++) {
      timeText.push(hh[i >> 1] + ':' + mm[i & 1]);
    }
    console.log(resList);
    this.setData({
      orderList: resList.map(o => {
        o.created_time = new Date(o.created_time).Format()
        o.modified_time = new Date(o.modified_time).Format()
        o.payment_price = o.payment_price.toFixed(2);
        o.order_state = order_state_map.get(o.order_state)
        o.court_info = o.sku_list.map(sku => {
          return {
            court_name: o.courts.filter(court => court._id == sku.court_id)[0].court_name,
            time_text: timeText[sku.rid] + ' ~ ' + timeText[sku.rid + 1]
          }
        })
        return o;
      })
    })
    console.log(this.data.orderList);
    this.setData({ refresher: 0 })
    wx.hideLoading()
  },
  onChangeTab(ev) {
    this.loadOrderData(this.data.tabs[ev.detail.index].searchData);
  },
  showDetail(ev) {
    wx.navigateTo({
      url: `/pages/user/order/detail?orderId=${ev.currentTarget.dataset.orderid}`,
    })
  },
  onPullDownRefresh() {
    this.loadOrderData();
  },
})